﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BBPA.Admin.Sys.Orders.Buying
{
    public partial class Form : FormPage
    {
        BLL.Orders bll = new BLL.Orders();
        Model.Orders model = new Model.Orders();
        //
        BLL.V_Orders_Goods bllV_Orders_Goods = new BLL.V_Orders_Goods();
        BLL.Orders_Goods bllOrders_Goods = new BLL.Orders_Goods();
        //
        BLL.Goods bllGoods = new BLL.Goods();
        BLL.Supplier bllSupplier = new BLL.Supplier();
        BLL.Orders_State_Log bllOrders_State_Log = new BLL.Orders_State_Log();
        //
        List<Model.V_Orders_Goods> listModelV_Orders_Goods = new List<Model.V_Orders_Goods>();
        //
        /// <summary>
        /// 实际联盟采购价格合计
        /// </summary>
        protected decimal ActualBuyPriceSum = 0;
        protected string IsDelivery = "", IsDeliveryStr="采购";
        decimal thisSupplier_ExpectBuyPriceSum = 0, thisSupplier_ActualBuyPriceSum=0;
        protected void Page_Load(object sender, EventArgs e) {
            IsDelivery = DataTypePlus.requestString(Request.QueryString["IsDelivery"]);
            if (IsDelivery == "0") IsDeliveryStr = "收货";
        }
        /// <summary>
        /// 初始化本页Model
        /// </summary>
        public override void Page_Load_DefaultModel() { model = bll.GetModel(Master.id); }
        /// <summary>
        /// 初始化表单
        /// </summary>
        public override void Form_Default()
        {
            Master.HideSubmit();
        }
        /// <summary>
        /// 绑定表单数据【修改时用】
        /// </summary>
        public override void Form_Bind()
        {
            rp_Goods_Bing();
            ((Label)rp_Goods.Controls[rp_Goods.Controls.Count - 1].FindControl("lb_ExpectPay")).Text = StringPlus.showMoney(model.ExpectPay);
        }
        /// <summary>
        /// 提交
        /// </summary>
        public override void Form_Submit()
        {
            foreach (RepeaterItem item in rp_Goods.Items)
            {
                int ActualAmount = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_ActualAmount")).Text);
                int ActualGiftNumber = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_ActualGiftNumber")).Text);
                decimal BuyPrice = DataTypePlus.requestDecimal(((TextBox)item.FindControl("tb_BuyPrice")).Text);
                //
                int _id = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_id")).Text);
                Model.Orders_Goods modelOrders_Goods = bllOrders_Goods.GetModel(_id);
                //修改价格
                Model.Goods modelGoods = bllGoods.GetModel(modelOrders_Goods.GoodsID);
                if (modelGoods.BuyPrice != BuyPrice)
                {
                    decimal old_BuyPrice = modelGoods.BuyPrice;
                    //进价BuyPrice
                    modelGoods.BuyPrice = BuyPrice;
                    //自动计算SellPrice
                    //decimal new_SellPrice = modelGoods.BuyPrice * modelGoods.SellPrice / old_BuyPrice;
                    //if (new_SellPrice > 10) new_SellPrice = Math.Round(new_SellPrice, 1);
                    modelGoods.SellPrice = modelGoods.BuyPrice;
                    bllGoods.Update(modelGoods);
                    BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Goods, modelGoods.id, EnumHelper.OperateType.Update, "修改进价为" + BuyPrice + "，售价为" + modelGoods.BuyPrice);
                }
                //修改实际采购数据
                modelOrders_Goods.ActualAmount = ActualAmount;
                modelOrders_Goods.ActualGiftNumber = ActualGiftNumber;
                //清空待点货数量
                modelOrders_Goods.WaitSupplierCheckNum = 0;
                bllOrders_Goods.Update(modelOrders_Goods);
            }
            Form_Bind();
        }

        void rp_Goods_Bing()
        {
            ActualBuyPriceSum = 0;
            string sql = "OrdersID=" + Master.id;

            if (IsDelivery != "") sql += " and IsDelivery=" + IsDelivery;

            sql += " order by IsDelivery desc,SupplierID, HasBuy";
            listModelV_Orders_Goods = bllV_Orders_Goods.GetModelList(sql);

            rp_Goods.DataSource = listModelV_Orders_Goods;
            rp_Goods.DataBind();
            Master.ScriptManager_js("Event_Amount_change();");
        }
        protected void rp_Goods_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int prevSupplierID = 0;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Model.V_Orders_Goods rowData = (Model.V_Orders_Goods)e.Item.DataItem;
                //
                //供货商
                if (e.Item.ItemIndex > 0 && DataTypePlus.requestInt(rowData.SupplierID) ==DataTypePlus.requestInt( listModelV_Orders_Goods[e.Item.ItemIndex-1].SupplierID))
                {
                    e.Item.FindControl("tr_SupplierName").Visible =  false;
                } 
                prevSupplierID = DataTypePlus.requestInt(rowData.SupplierID);
                //
                TextBox tb_ActualAmount = (TextBox)e.Item.FindControl("tb_ActualAmount");
                tb_ActualAmount.Text = rowData.ActualAmount.ToString();
                if (!rowData.HasBuy && rowData.ActualAmount == 0) tb_ActualAmount.Text = rowData.ExpectAmount.ToString();

                //小计
                decimal thisGoods_ActualBuyPriceSum = rowData.IsLatePay ? 0 : rowData.HasBuy ? rowData.ActualBuyPriceSum : BBPA.BLL.Goods.GetBuyPriceSum(rowData.GoodsID, rowData.ActualAmount);
                ((Label)e.Item.FindControl("lb_Goods_ActualBuyPriceSum")).Text = StringPlus.showCoin(thisGoods_ActualBuyPriceSum);
                thisSupplier_ExpectBuyPriceSum += rowData.ExpectBuyPriceSum;
                thisSupplier_ActualBuyPriceSum += thisGoods_ActualBuyPriceSum;
                if (e.Item.ItemIndex == listModelV_Orders_Goods.Count-1 || (e.Item.ItemIndex < listModelV_Orders_Goods.Count-1 && DataTypePlus.requestInt(rowData.SupplierID) != DataTypePlus.requestInt(listModelV_Orders_Goods[e.Item.ItemIndex + 1].SupplierID)))
                {
                    ((Label)e.Item.FindControl("lb_Supplier_ExpectBuyPriceSum")).Text = StringPlus.showCoin(thisSupplier_ExpectBuyPriceSum);
                    ((Label)e.Item.FindControl("lb_Supplier_ActualBuyPriceSum")).Text = StringPlus.showCoin(thisSupplier_ActualBuyPriceSum);
                    thisSupplier_ExpectBuyPriceSum = thisSupplier_ActualBuyPriceSum = 0;
                }
                else e.Item.FindControl("tr_xiaoji").Visible = false;
                //((TextBox)e.Item.FindControl("tb_id")).Text = rowData.id.ToString();
                //((TextBox)e.Item.FindControl("tb_BuyPrice")).Text = StringPlus.showCoin(rowData.SellPrice);
                //((TextBox)e.Item.FindControl("tb_ActualAmount")).Text = rowData.ActualAmount.ToString();
                //((TextBox)e.Item.FindControl("tb_ActualGiftNumber")).Text = rowData.ActualGiftNumber.ToString();
                //
                ActualBuyPriceSum += rowData.ActualAmount * DataTypePlus.requestDecimal(rowData.BuyPrice);
            }
        }

        protected void rp_Goods_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "HasBuy" || e.CommandName == "HasBuy0")//判断这个Item里哪个控件响应的这个事件  
            {
                int _id = DataTypePlus.requestInt(e.CommandArgument);//获取Item传过来的参数  
                Model.Orders_Goods modelOrders_Goods = bllOrders_Goods.GetModel(_id);
                //实际采购数量
                modelOrders_Goods.ActualAmount = DataTypePlus.requestInt(((TextBox)e.Item.FindControl("tb_ActualAmount")).Text);
                if (e.CommandName == "HasBuy0") modelOrders_Goods.ActualAmount = 0;
                bllOrders_Goods.Update(modelOrders_Goods);
                //
                Model.Goods modelGoods = bllGoods.GetModel(modelOrders_Goods.GoodsID);
                //Buy
                modelOrders_Goods.ActualBuyPrice = modelGoods.BuyPrice;
                modelOrders_Goods.ActualBuyPriceSum = BLL.Goods.GetBuyPriceSum(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                modelOrders_Goods.ActualBuyDiscount = BLL.Goods.GetBuyDiscount(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                modelOrders_Goods.ActualBuyGiftNumber = BLL.Goods.GetGiftNumberBuy(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                //Sell
                modelOrders_Goods.ActualPrice = modelGoods.SellPrice;
                modelOrders_Goods.ActualPriceSum = BLL.Goods.GetSellPriceSum(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                modelOrders_Goods.ActualDiscount = BLL.Goods.GetSellDiscount(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                modelOrders_Goods.ActualGiftNumber = BLL.Goods.GetGiftNumberSell(modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                bllOrders_Goods.Update(modelOrders_Goods);//先更新，为了Pay获取数据用
                //

                Model.Supplier modelSupplier = bllSupplier.GetModel(modelGoods.SupplierID);
                if (e.CommandName == "HasBuy")
                {
                    //Pay
                    if (modelSupplier == null || (modelSupplier != null && !modelSupplier.IsLatePay) || (modelSupplier != null && modelSupplier.id == 0))
                        modelOrders_Goods.ActualPay = modelOrders_Goods.ActualBuyPriceSum;//现场实际支付
                    else
                    {
                        if (modelSupplier != null && modelSupplier.id > 0)//后付费
                            BLL.Account_Change_Log.Add(EnumHelper.UserType.Supplier, modelGoods.SupplierID, EnumHelper.AccountChangeReason.Supplier_GetPay, _id, modelOrders_Goods.ActualBuyPriceSum);//给供货商
                    }
                }
                modelOrders_Goods.HasBuy = true;
                bllOrders_Goods.Update(modelOrders_Goods);
                if (e.CommandName == "HasBuy" && model.Ischeck!=2)
                {
                    //Stat
                    decimal Profits = modelOrders_Goods.ActualPriceSum - modelOrders_Goods.ActualBuyPriceSum;
                    //Goods
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Goods_Stat, EnumHelper.Goods_Stat_colum.Orders_GoodsAmoun, modelOrders_Goods.GoodsID, modelOrders_Goods.ActualAmount);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Goods_Stat, EnumHelper.Goods_Stat_colum.BuyPrice, modelOrders_Goods.GoodsID, modelOrders_Goods.ActualBuyPriceSum);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Goods_Stat, EnumHelper.Goods_Stat_colum.SellPrice, modelOrders_Goods.GoodsID, modelOrders_Goods.ActualPriceSum);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Goods_Stat, EnumHelper.Goods_Stat_colum.Profits, modelOrders_Goods.GoodsID, Profits);
                    //Orders
                    BLL.Stat.Increase1(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.Orders_GoodsCount, Master.id);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.Orders_GoodsAmount, modelOrders_Goods.ActualAmount, Master.id);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.BuyPrice, Master.id, modelOrders_Goods.ActualBuyPriceSum);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.SellPrice, Master.id, modelOrders_Goods.ActualPriceSum);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.Profits, Master.id, Profits);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Orders_Stat, EnumHelper.Orders_Stat.Pay, Master.id, modelOrders_Goods.ActualPay);
                    //Store
                    BLL.Stat.Increase1(EnumHelper.StatTable.Store_Stat, EnumHelper.Store_Stat.Orders_GoodsCount, model.StoreID);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Store_Stat, EnumHelper.Store_Stat.Orders_GoodsAmount, modelOrders_Goods.ActualAmount, model.StoreID);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Store_Stat, EnumHelper.Store_Stat.OrdersSellPrice, model.StoreID, modelOrders_Goods.ActualPriceSum);
                    BLL.Stat.IncreaseN(EnumHelper.StatTable.Store_Stat, EnumHelper.Store_Stat.Profits, model.StoreID, Profits);
                    //Supplier
                    if (modelSupplier != null && modelSupplier.id > 0)
                    {
                        BLL.Stat.Increase1(EnumHelper.StatTable.Supplier_Stat, EnumHelper.Supplier_Stat.Orders_GoodsCount, modelSupplier.id);
                        BLL.Stat.IncreaseN(EnumHelper.StatTable.Supplier_Stat, EnumHelper.Supplier_Stat.Orders_GoodsAmount, modelOrders_Goods.ActualAmount, modelSupplier.id);
                        BLL.Stat.IncreaseN(EnumHelper.StatTable.Supplier_Stat, EnumHelper.Supplier_Stat.BuyPrice, modelSupplier.id, modelOrders_Goods.ActualBuyPriceSum);
                        BLL.Stat.IncreaseN(EnumHelper.StatTable.Supplier_Stat, EnumHelper.Supplier_Stat.SellPrice, modelSupplier.id, modelOrders_Goods.ActualPriceSum);
                        BLL.Stat.IncreaseN(EnumHelper.StatTable.Supplier_Stat, EnumHelper.Supplier_Stat.Profits, modelSupplier.id, Profits);
                    }
                }
                //
                string sql_check_allFinish = "OrdersID=" + Master.id + " and HasBuy=0";
                if (IsDelivery != "")
                {
                    if (IsDelivery == "0") sql_check_allFinish += " and IsDelivery=0";
                    if (IsDelivery == "1") sql_check_allFinish += " and IsDelivery=1";
                }
                if (bllV_Orders_Goods.GetRecordCount(sql_check_allFinish) == 0) BuyFinish();
                else Form_Bind();
                Form_Bind();
            }
        }
        void BuyFinish()
        {
            //model.ActualBuyPriceSum = model.ActualPriceSum = model.ActualPay = 0;
            foreach (Model.V_Orders_Goods modelV_Orders_Goods in bllV_Orders_Goods.GetModelList("OrdersID=" + Master.id + " and IsDelivery=" + IsDelivery))
            {
                model.ActualBuyPriceSum += modelV_Orders_Goods.ActualBuyPriceSum;
                model.ActualPriceSum += modelV_Orders_Goods.ActualPriceSum;
                
                if(modelV_Orders_Goods.IsDelivery)model.ActualPay_Delivery += modelV_Orders_Goods.ActualPay;
                else model.ActualPay += modelV_Orders_Goods.ActualPay;
            }
            if (IsDelivery != "")
            {
                if (IsDelivery == "0") model.HasPay=true;
                if (IsDelivery == "1")
                {
                    model.HasPay_Delivery = true;
                    model.IsBuyMoneyOK_Delivery = model.ExpectPay_Delivery == model.ActualPay_Delivery;
                }
            }
            if (bllV_Orders_Goods.GetRecordCount("OrdersID=" + Master.id + " and HasBuy=0") == 0) model.State = (int)EnumHelper.OrdersState.BuyFinish;
            
            //支付
            //CallBak<int> callBak_BuySuccess = BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, model.StoreID, EnumHelper.AccountChangeReason.Success_BuyOrders, Master.id, model.ActualPriceSum);//扣孕婴店
            //if (!callBak_BuySuccess.IsSuccess) { Master.ScriptManager_Alert_float(callBak_BuySuccess.ErrMsg, false); return; }

            model.Ischeck = 1;
            bll.Update(model);
            BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, IsDeliveryStr + "完成");
            ////
            if (model.State == (int)EnumHelper.OrdersState.BuyFinish)
            {
                Model.Orders_State_Log modelLog = new Model.Orders_State_Log();
                modelLog.OrdersID = Master.id;
                modelLog.State = (int)EnumHelper.OrdersState.BuyFinish;
                int LogID = bllOrders_State_Log.Add(modelLog);
                BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Orders_State_Log, LogID, EnumHelper.OperateType.Add, "订单支付完成");
            }

            Master.SubmitOK("本订单" + IsDeliveryStr + "完毕");
        }


    }
}